package com.by_man.repository;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_health_records.image.BitmapManager;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理所有的数据获取及更新
 * Created by man on 2017-03-03.
 */
public class NetworkDataManager {
    private RequestQueue rQueue;
    // 记录请求次数,重要请求不超过三次，次要数据不超过两次
    public static int BPNum = 3;
    public static int OneBPNum = 3;
    public static int BSNum = 3;
    public static int ThereBSNum = 3;
    public static int DocNum = 3;
    public static int NewActivityNum = 3;
    public static int HealthAdviceNum = 3;
    public static int LatelyActivityNum = 3;
    public static int SelfInfosNum = 3;
    public NetworkDataManager(RequestQueue rQueue) {
        this.rQueue = rQueue;
        //  初始时请求一次数据
        initData();
    }

    private void initData() {
        // 保持基本页面生成
        // 获取医生信息
        getSelfInfosByNetwork(null);
        getAllDoctorByNetwork();
        getAllNewActivityByNetwork();
        getAllLatelyActivityByNetwork();
    }

    /***************************************************************************************************
     * 血压
     ***************************************************************************************************/
    // 网络请求获取一次血压心率记录
    public void getOneBloodPressureRecordByNetwork() {
        if (OneBPNum >= 1) {
            OneBPNum --;
            final Gson gson = new Gson();
            List<Map<String, Object>> testlist = new ArrayList<Map<String, Object>>();
            Map<String, Object> test1 = new HashMap<String, Object>();
            test1.put("id", 2);
            testlist.add(test1);
            String dataString = gson.toJson(testlist).toString();
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("token", UserInfos.token);
            params.put("json", dataString);
            // 将请求参数封装到json对象中
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.One_BloodPressure_Record, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArrayResponse) {
                            Log.d("Response", jsonArrayResponse.toString());
                            UserInfos.One_BloodPressure_Record = jsonArrayResponse;
                            getAllBloodPressreRecordByNetword();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("Error", volleyError.getMessage(), volleyError);
                           getOneBloodPressureRecordByNetwork();
                        }
                    });
            rQueue.add(postJsonArrayRequest);
        }
    }

    // 网络请求获取所有血压心率记录
    public void getAllBloodPressreRecordByNetword() {
        if (BPNum >= 1) {
            BPNum --;
            // 请求数据
            final Gson gson = new Gson();
            List<Map<String, Object>> testlist = new ArrayList<Map<String, Object>>();
            Map<String, Object> test1 = new HashMap<String, Object>();
            test1.put("id", 2);
            testlist.add(test1);
            String dataString = gson.toJson(testlist).toString();
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("token", UserInfos.token);
            params.put("json", dataString);
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.All_BloodPressure_Record, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArrayResponse) {
                            Log.d("Response", jsonArrayResponse.toString());
                            UserInfos.All_BloodPressure_Record = jsonArrayResponse;
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("Error", volleyError.getMessage(), volleyError);
                            getAllBloodPressreRecordByNetword();
                        }
                    });
            rQueue.add(postJsonArrayRequest);
        }
    }

    // 上传手动输入血压信息
    public void uploadManualBloodPressreRecord(String record) {
        HashMap<String,String> params = new HashMap<String, String>();
        params.put("token", UserInfos.token);
        params.put("json", record);
        // 将请求参数封装到json对象中
        JSONObject jsonObject = new JSONObject(params);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, IpAddress.Manual_BloodPressure_Record, jsonObject,
                new Response.Listener<JSONObject>() {   // 求情成功执行用户定义的回调方法
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Response", response.toString());
                        try {
                            boolean isInsert = false;
                            isInsert = response.getBoolean("isFull");
                            if(isInsert){
                                Log.i("ManualInputBP", "insert success");
                                // 缓存处理
                                LocalDataManager.showMessage("数据已成功回传");
                            }
                        } catch (JSONException je) {
                            je.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error", error.getMessage(), error);
                    }
                }
        );
        rQueue.add(jsonObjectRequest);
    }

    /*************************************************************************************************
     * 血糖
     *************************************************************************************************/
    public void getThreeBloodSugarRecordByNetwork() {
        if (ThereBSNum >= 1) {
            ThereBSNum --;
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("token", UserInfos.token);
            // 将请求参数封装到json对象中
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.Three_BloodSugar_Record, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArrayResponse) {
                            Log.d("Response", jsonArrayResponse.toString());
                            UserInfos.Three_BloodSugar_Record = jsonArrayResponse;
                            getAllBloodSugarRecordByNetwork();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("Error", volleyError.getMessage(), volleyError);
                            getThreeBloodSugarRecordByNetwork();
                        }
                    });
            rQueue.add(postJsonArrayRequest);
        }
    }

    public void getAllBloodSugarRecordByNetwork() {
        if (BSNum >= 1) {
            BSNum --;
            HashMap<String, String> params = new HashMap<>();
            params.put("token", UserInfos.token);
            // 将请求参数封装到json对象中
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.All_BloodSugar_Record, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArrayResponse) {
                            Log.d("Response", jsonArrayResponse.toString());
                            UserInfos.All_BloodSugar_Record = jsonArrayResponse;
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("Error", volleyError.getMessage(), volleyError);
                            getAllBloodSugarRecordByNetwork();
                        }
                    });
            rQueue.add(postJsonArrayRequest);
        }
    }

    // 上传手动输入血糖信息
    public void uploadManualBloodSugarRecord(String record) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("token", UserInfos.token);
        params.put("json", record);
        // 将请求参数封装到json对象中
        JSONObject jsonObject = new JSONObject(params);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, IpAddress.Manual_BloodSugar_Record, jsonObject,
                new Response.Listener<JSONObject>() {   // 求情成功执行用户定义的回调方法
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Response", response.toString());
                        try {
                            boolean isInsert = false;
                            isInsert = response.getBoolean("isFull");
                            if (isInsert) {
                                // 进行缓存操作
                                LocalDataManager.showMessage("保存血糖数据成功");
                            }
                        }catch (JSONException je) {
                            je.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error", error.getMessage(), error);
                    }
                }
        );
        rQueue.add(jsonObjectRequest);
    }


    /*************************************************************************************************
     * 健康顾问
     *************************************************************************************************/
    public void getAllDoctorByNetwork() {
        if (DocNum >= 1) {
            DocNum --;
            HashMap<String, String> params = new HashMap<>();
            params.put("token", UserInfos.token);
            // 将请求参数封装到json对象中
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.All_Doctor, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArrayResponse) {
                            Log.d("Response", jsonArrayResponse.toString());
                            UserInfos.All_Doctor = jsonArrayResponse;
                            // 请求别的数据
                            getOneBloodPressureRecordByNetwork();

                            getThreeBloodSugarRecordByNetwork();

                            getAllHealthAdviceRecordByNetwork();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("Error", volleyError.getMessage(), volleyError);
                        }
                    });
            rQueue.add(postJsonArrayRequest);
        }
    }

    /*************************************************************************************************
     * 健康建议
     *************************************************************************************************/
    public void getAllHealthAdviceRecordByNetwork() {
        if (HealthAdviceNum >= 1) {
            HealthAdviceNum --;
            HashMap<String, String> params = new HashMap<>();
            params.put("token", UserInfos.token);
            // 将请求参数封装到json对象中
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.All_HealthAdvice_Record, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArrayResponse) {
                            Log.d("Response", jsonArrayResponse.toString());
                            UserInfos.All_HealthAdvice_Record = jsonArrayResponse;
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("Error", volleyError.getMessage(), volleyError);
                        }
                    });
            rQueue.add(postJsonArrayRequest);
        }
    }

    /*************************************************************************************************
     * 上传文件
     *************************************************************************************************/


    /***********************************************************************************************
     * 载入网络图像
     ***********************************************************************************************/


    /***********************************************************************************************
     * 会员活动
     ***********************************************************************************************/
    public void getAllNewActivityByNetwork() {
        if (NewActivityNum >= 1) {
            NewActivityNum --;
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("token", UserInfos.token);
            // 将请求参数封装到json对象中
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.All_New_Activity, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArrayResponse) {
                            Log.d("Response", jsonArrayResponse.toString());
                            UserInfos.All_New_Activity = jsonArrayResponse;
                            // 取出所有详情
                            JSONObject jsonObject;
                            String name;
                            try {
                                for (int i = 0; i < jsonArrayResponse.length(); i++) {
                                    jsonObject = (JSONObject) jsonArrayResponse.get(i);
                                    name = jsonObject.getString("meeting_name");
                                    getOneNewActivityDetailByNetworkByNetwork(name);
                                    getActivityNumberByNetwork(name);
                                }

                                // 取出服务号
                                getServicePhoneByNetwork();
                                // 取出公众号
                                getPublicNumberByNetwork();

                            } catch (JSONException je) {
                                je.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("Error", volleyError.getMessage(), volleyError);
                            getAllNewActivityByNetwork();
                        }
                    });
            rQueue.add(postJsonArrayRequest);
        }
    }

    public void getAllLatelyActivityByNetwork() {
        if (LatelyActivityNum >= 1) {
            LatelyActivityNum --;
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("token", UserInfos.token);
            // 将请求参数封装到json对象中
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST,  IpAddress.All_Lately_Activity, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArrayResponse) {
                            Log.d("Response", jsonArrayResponse.toString());
                            UserInfos.All_Lately_Activity = jsonArrayResponse;
                            // 取出所有详情
                            JSONObject jsonObject;
                            String name;
                            try {
                                for (int i = 0; i < jsonArrayResponse.length(); i++) {
                                    jsonObject = (JSONObject) jsonArrayResponse.get(i);
                                    name = jsonObject.getString("title");
                                    getOneLatelyActivityDetailByNetworkByNetwork(name);
                                }
                            } catch (JSONException je) {
                                je.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("Error", volleyError.getMessage(), volleyError);
                            getAllLatelyActivityByNetwork();
                        }
                    });
            rQueue.add(postJsonArrayRequest);
        }
    }

    public void getOneNewActivityDetailByNetworkByNetwork(String name) {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", UserInfos.token);
        params.put("arg", name);
        final String n = name;
        // 将请求参数封装到json对象中
        JSONObject jsonObject = new JSONObject(params);
        PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.New_Activity_Detail, jsonObject,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArrayResponse) {
                        Log.d("Response", jsonArrayResponse.toString());
                        UserInfos.All_New_Activity_Detail.put(n, jsonArrayResponse);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("Error", volleyError.getMessage(), volleyError);
                    }
                });
        rQueue.add(postJsonArrayRequest);
    }

    public void getOneLatelyActivityDetailByNetworkByNetwork(String name) {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", UserInfos.token);
        params.put("arg", name);
        final String n = name;
        // 将请求参数封装到json对象中
        JSONObject jsonObject = new JSONObject(params);
        PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.Lately_Activity_Detail, jsonObject,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArrayResponse) {
                        Log.d("Response", jsonArrayResponse.toString());
                        UserInfos.All_Lately_Activity_Detail.put(n, jsonArrayResponse);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("Error", volleyError.getMessage(), volleyError);
                    }
                });
        rQueue.add(postJsonArrayRequest);
    }

    public void getActivityNumberByNetwork(String name) {
        final HashMap<String, String> params = new HashMap<String, String>();
        params.put("token", UserInfos.token);
        params.put("arg", name);
        final String n = name;
        // 将请求参数封装到json对象中
        JSONObject jsonObject = new JSONObject(params);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, IpAddress.Sign_Up, jsonObject,
                new Response.Listener<JSONObject>() {   // 求情成功执行用户定义的回调方法
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Response", response.toString());
                        UserInfos.Activity_Number.put(n, response);
                    }
                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error", error.getMessage(), error);
                    }
                }
        );
        rQueue.add(jsonObjectRequest);
    }

    /***********************************************************************************************
     * 服务电话、公众号、 个人信息
     ***********************************************************************************************/
    public void getServicePhoneByNetwork() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("token", UserInfos.token);
        // 将请求参数封装到json对象中
        JSONObject jsonObject = new JSONObject(params);
        PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.Service_Phone, jsonObject,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArrayResponse) {
                        Log.d("Response", jsonArrayResponse.toString());
                        UserInfos.Service_Phone = jsonArrayResponse;
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("Error", volleyError.getMessage(), volleyError);
                    }
                });
        rQueue.add(postJsonArrayRequest);
    }

    public void getPublicNumberByNetwork() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("token", UserInfos.token);
        // 将请求参数封装到json对象中
        JSONObject jsonObject = new JSONObject(params);
        PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.Public_Num, jsonObject,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArrayResponse) {
                        Log.d("Response", jsonArrayResponse.toString());
                        UserInfos.Public_Number = jsonArrayResponse;
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("Error", volleyError.getMessage(), volleyError);
                    }
                });
        rQueue.add(postJsonArrayRequest);
    }

    public void getSelfInfosByNetwork(final Handler handler) {
        if (SelfInfosNum >= 1) {
            SelfInfosNum --;
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("token", UserInfos.token);
            // 将请求参数封装到json对象中
            JSONObject jsonObject = new JSONObject(params);
            PostJsonArrayRequest postJsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.Self_Infos, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArrayResponse) {
                            Log.d("Response", jsonArrayResponse.toString());
                            UserInfos.Self_Infos = jsonArrayResponse;
                            if (handler != null) {  // 提醒更新界面
                                Message message = Message.obtain(handler);
                                message.what = 125;
                                message.sendToTarget();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("Error", volleyError.getMessage(), volleyError);
                            getSelfInfosByNetwork(null);
                        }
                    });
            rQueue.add(postJsonArrayRequest);
        }
    }

    public void updateSelfInfos(String jsStr,final Handler handler) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("token", UserInfos.token);
        params.put("json", jsStr);
        // 将请求参数封装到json对象中
        JSONObject jsonObject = new JSONObject(params);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, IpAddress.Update_Self_Infos,
                jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            boolean isFull = false;
                            isFull = jsonObject.getBoolean("isFull");
                            if (isFull) {
                                LocalDataManager.showMessage("更新个人信息成功！");
                                getSelfInfosByNetwork(handler);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("UpdateSelfInfos",volleyError.getMessage(),volleyError);
                    }
                });
        rQueue.add(jsonObjectRequest);
    }
}
